package com.zhanhong.opencvdemo.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhanhong.opencvdemo.value.FilePath;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogUtils {


    public static final String TIME_FORMAT = "_yyyyMMdd_HHmmss";

    public static String saveJsonToFile(Object content, String tag) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String json = gson.toJson(content);
        File logDir = createDir(FilePath.LOG_DIR);
        String timeStamp = new SimpleDateFormat(TIME_FORMAT, Locale.CHINA).format(new Date());
        File saveFile = new File(logDir.getPath(), tag + timeStamp + ".txt");
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(saveFile);
            outStream.write(json.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private static File createDir(String dirPath) {
        final File fileDir = new File(dirPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return fileDir;
    }

}
